package com.maimang.platform.controller.system;

import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.entity.SysFilePlay;
import com.maimang.platform.common.entity.SysFiles;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.exception.BusinessException;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.page.TableDataInfo;
import com.maimang.platform.common.service.SysFilePlayService;
import com.maimang.platform.common.service.SysFilesService;
import com.maimang.platform.common.utils.ExcelUtil;
import com.maimang.platform.common.utils.bean.BeanUtils;
import com.maimang.platform.common.utils.file.FileUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * 文件上传操作处理
 *
 * @author Rocky
 * @date 2019-01-19
 */
@Controller
@RequestMapping("/system/files")
@Api(value = "文件上传接口", description = "文件上传操作处理")
public class SysFilesController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SysFilesController.class);
	private String prefix = "system/files";

	@Autowired
	private SysFilesService sysFilesService;
	@Autowired
	private SysFilePlayService sysFilePlayService;

	@RequiresPermissions("system:files:view")
	@GetMapping()
	public String files() {
		return prefix + "/files";
	}

	/**
	 * listOrder
	 * 查询文件上传列表
	 */
	@RequiresPermissions("system:files:list")
	@ApiOperation(value = "文件上传列表", notes = "文件对象可以为null")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysFiles files) {
		startPage();
		List<SysFiles> list = sysFilesService.selectSysFilesList(files);
		return getDataTable(list);
	}

	/**
	 * 查询文件上传列表(不带显示的)
	 */
	@RequiresPermissions("system:files:list")
	@PostMapping("/listWithNoSave")
	@ResponseBody
	public TableDataInfo listWithNoSave(SysFiles files) {
		startPage();
		List<SysFiles> list = sysFilesService.selectSysFilesListNoSave(files);
		return getDataTable(list);
	}

	/**
	 * 导出文件上传列表
	 */
	@RequiresPermissions("system:files:export")
	@ApiOperation(value = "导出文件上传列表", notes = "将已上传的文件信息列表导出到Excel")
	@PostMapping("/export")
	@ResponseBody
	public Result export(SysFiles files) {
		List<SysFiles> list = sysFilesService.selectSysFilesList(files);
		ExcelUtil<SysFiles> util = new ExcelUtil<>(SysFiles.class);
		return util.exportExcel(list, "上传文件信息");
	}

	/**
	 * 新增文件上传
	 */
	@GetMapping("/add")
	public String add(ModelMap modelMap) {
		SysFiles files = new SysFiles();
		modelMap.put("files", files);
		return prefix + "/add";
	}

	/**
	 * 新增保存文件上传
	 */
	@RequiresPermissions("system:files:add")
	@Log(title = "文件上传", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(MultipartFile file, SysFiles files) {
		int result = 0;
		Boolean isFile = false;
		try {
			files = dealFile(file, files);
			if (files.getUpdateFlag() == 1 && files.getFileId() > 0) {//修改
				if (file != null) {
					isFile = true;
				}
				result = sysFilesService.updateSysFiles(files, isFile);
			} else {//新增
				result = sysFilesService.insertSysFiles(files);
			}
			if (file != null && !"2".equals(files.getType())) {
				File desc = FileUploadUtils.getAbsoluteFile(FileUploadUtils.getDefaultBaseDir(), files.getUrl());
				file.transferTo(desc);
			}
		} catch (Exception e) {
			log.error("保存失败，请检查后重试！", e);
			return error(e.getMessage());
		}
		return toResult(result);
	}

	/**
	 * 新增保存文件上传
	 */
	@RequiresPermissions("file:add")
	@Log(title = "文件上传", businessType = BusinessType.INSERT)
	@PostMapping("/addFileToShow")
	@ResponseBody
	public Result addFileToShow(String list, Long channelCode) {
		String[] ids = list.split(",");
		int result = 0;
		if (StringUtils.isEmpty(ids) || ids.length < 1) {
			throw new BusinessException("文件不能为空！");
		}
		int orderNum = 0;
		SysFilePlay lastModel = sysFilePlayService.selectMaxLimit(channelCode);
		if (lastModel != null) {//取到最大的排序
			orderNum = lastModel.getOrderNum();
		}
		for (int i = 0; i < ids.length; i++) {
			SysFiles files = sysFilesService.selectSysFilesById(Long.valueOf(ids[i]));
			if (files == null) {
				throw new BusinessException("文件已被删除！");
			}
			SysFilePlay playsOrder = new SysFilePlay();
			BeanUtils.copyBeanProp(playsOrder, files);
			playsOrder.setChannelCode(channelCode);
			playsOrder.setOrderNum(orderNum++);
			result = sysFilePlayService.insertFilePlay(playsOrder);
		}
		return toResult(result);
	}

	private SysFiles dealFile(MultipartFile file, SysFiles files) throws BusinessException {
		if (file == null || "2".equals(files.getType())) return files;
		String suffix = FileUploadUtils.getSuffixName(file.getOriginalFilename());
		if (StringUtils.isEmpty(suffix)) throw new BusinessException("缺少后缀");
		String name = FileUploadUtils.getDefaultBaseDir() + files.getFileName() + "." + suffix;
		files.setUrl(name);
		files.setSuffix(suffix);
		files.setCreateUser(getLoginName());
		files.setCreateUserName(getSysUser().getUserName());
		return files;
	}

	private SysFilePlay getSysFilePlayModel(SysFiles files, Long channelCode) {
		SysFilePlay filePlay = new SysFilePlay();
		filePlay.setChannelCode(channelCode);
		filePlay.setContent(files.getContent());
		filePlay.setFileName(files.getFileName());
		filePlay.setUrl(files.getUrl());
		filePlay.setTypes(files.getType());
		filePlay.setSuffix(files.getSuffix());
		return filePlay;
	}

	/**
	 * 修改文件上传
	 */
	@GetMapping("/edit/{fileId}")
	public String edit(@PathVariable("fileId") Long fileId, ModelMap modelMap) {
		SysFiles files = sysFilesService.selectSysFilesById(fileId);
		modelMap.put("files", files);
		String fileUrl = "/profile/" + files.getFileName() + "." + files.getSuffix();
		modelMap.put("fileUrl", fileUrl);
		return prefix + "/add";
	}

	/**
	 * 修改保存文件上传
	 */
	@RequiresPermissions("system:files:edit")
	@Log(title = "文件上传", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(SysFiles files) {
		return toResult(sysFilesService.updateSysFiles(files, false));
	}

	/**
	 * 删除文件上传
	 */
	@RequiresPermissions("system:files:remove")
	@Log(title = "文件上传", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(String ids) {
		return toResult(sysFilesService.deleteSysFilesByIds(ids));
	}

	@RequestMapping("/listOrder")
	@ResponseBody
	public TableDataInfo getShow(SysFilePlay filePlay) {
		List<SysFilePlay> playOrderList = sysFilePlayService.selectFilePlayList(filePlay);
		return getDataTable(playOrderList);
	}

	@RequestMapping("/listOrderPage")
	public String listOrder() {
		return prefix + "/orderShow";
	}

	/**
	 * 检验文件名是否唯一
	 *
	 * @param files
	 * @return
	 */
	@PostMapping("/checkFileNameUnqiue")
	@ResponseBody
	public String checkFileNameUnqiue(SysFiles files) {
		return sysFilesService.checkFileNameUnqiue(files);
	}

	@RequestMapping("/show/{id}")
	public String show(@PathVariable("id") Long id, Model model) {
		if (id != null && id > 0) {
			model.addAttribute("id", id);
		}
		return prefix + "/lunbo";
	}

}